package com.wzy.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 描述 :
 * 创建一个线程池,如果有客户连接,就创建一个线程与之通信
 * 创建人    Wzy
 * 创建时间: 2020-05-20  3:28
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动");

        while (true) {
            //监听等待客户端连接
            final Socket accept = serverSocket.accept();
            System.out.println("连接到一个客户端");

            threadPool.submit(() -> {
                handler(accept);
            });
        }

    }

    public static void handler(Socket socket) {
        byte[] bytes = new byte[1024];
        //通过socket 获取输入流
        try {
            InputStream inputStream = socket.getInputStream();
            while (true) {
                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(new String(bytes, 0, read));//输出客户端发送的数据
                } else {
                    break;
                }
            }

            System.out.println("关闭客户端连接");
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
